import {
  showInformationMessage,
  downloadNPMPackageInfoMsg,
} from "@ap/util/vscode/message";
import getFilePath from "@ap/util/vscode/getFilePath";
import * as vscode from "vscode";
import { arenaErrorMsg } from "../util/vscode/errorMsg";
import { CommandId } from "@ap/command";

export default async function downloadNPMPackage(name: string, view: string) {
  // 获取工作区的文件夹的路径。
  const workspaceFolder = getFilePath();
  // 如果没有找到工作区文件夹，则终止执行
  if (!workspaceFolder) {
    showInformationMessage(arenaErrorMsg.OPEN_WORKSPACE);
    vscode.commands.executeCommand(CommandId.ap_files_focusFilesExplorer);
    return;
  }
  // 检查是否可以创建项目信息消息
  if (!(await downloadNPMPackageInfoMsg(name, view))) {
    // 如果无法创建项目信息消息，则终止执行
    return;
  }

  // 创建一个ArenaPro专用终端
  const arenaTerminal = vscode.window.createTerminal({
    cwd: workspaceFolder,
    name: "ArenaPro",
    message: "神岛npm包名：" + name + " | 使用介绍： " + view,
    iconPath: vscode.Uri.parse(
      "https://static.codemao.cn/pickduck/HkblwwDdC.png?hash=FjCNOjP--1CsvhtLZVOTP2kWcRX2",
    ),
  });
  // 显示终端
  arenaTerminal.show();
  // 延迟100毫秒后，在终端中发送初始化项目的命令
  setTimeout(async () => {
    arenaTerminal.sendText(
      `npm --registry=https://mirrors.cloud.tencent.com/npm/ i ${name}@latest`,
      true,
    );
  }, 100);
}
